package com.miaoyi.controller;

import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;

@RestController
public class HelloController {
    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @RequestMapping("01-hello")
    public String sendMsg(String message) {
        //第一个参数是  topic+标签组成
        // 如果不想 写标签那么不写即可
        // 要是需要标签则语法 topic+:tag
        //第二个参数 消息内容
        SendResult sendResult = rocketMQTemplate.syncSend("01-boot:", message);//1、发送同步消息
       /* System.out.println(sendResult.getMsgId());
        System.out.println(sendResult.getSendStatus());*/
        return "success";
    }

    /**
     * 消费模式 一次性发送 同步发送 异步发送
     */

    //发送异步消息
    @RequestMapping("02-hello")
    public String sendMsg2(String message) {
        //rocketMQTemplate.syncSend("01-boot:", message);//1、发送同步消息
        //发送异步消息
        rocketMQTemplate.asyncSend("01-boot:", message, new SendCallback() {
            @Override
            public void onSuccess(SendResult sendResult) {
                System.out.println("成功");
            }

            @Override
            public void onException(Throwable throwable) {
                System.out.println("失败");

            }
        });

        return "success";
    }

    //一次性发送消息
    @RequestMapping("03-hello")
    public String sendMsg3(String message) {
        //一次性发送消息
        rocketMQTemplate.sendOneWay("01-boot:", message);

        return "success";
    }

    //测试集群广播模式发送
    @RequestMapping("04-hello")
    public String sendMsg4(String message) {
        //一次性发送消息
        rocketMQTemplate.sendOneWay("boot-model:", message);
        return "success";
    }

    //发送延迟消息
    @RequestMapping("05-hello")
    public String delay(String message) {

        MessageBuilder<String> messageBuilder = MessageBuilder.withPayload(message);
        //5000是超时时间  2是消息的延迟级别
        //messageDelayLevel=1s 5s 10s 30s 1m 2m 3m 4m 5m 6m 7m 8m 9m 10m 20m 30m 1h 2h
        rocketMQTemplate.syncSend("01-delay", messageBuilder.build(), 5000, 3);
        return "success";
    }

    //发送标签 sql 过滤消息
    @RequestMapping("06-hello")
    public String filter(String message) {
        rocketMQTemplate.syncSend("01-filter:Tag", message);
        return "success";
    }
    //发送 sql 过滤消息
    @RequestMapping("07-hello")
    public String filtersql(String message,String age) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("age",age);
        rocketMQTemplate.convertAndSend("boot-filter", message,map);
        return "success";
    }
}
